﻿using System;
using System.Collections.Generic;

using System.Text;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using MFD.SharePoint.SPBackup.Properties;
using System.IO;
using System.Collections;
using System.Diagnostics;

namespace MFD.SharePoint.SPBackup
{
    public class MFDSPBackup
    {
        
        
        

        public static bool BackupAllSites(SPFarm farm, Logger logger)
        {
            try
            {
                
                
                string rootFolder = Settings.Default.rootFolder;

                SPWebApplicationCollection webApps = farm.Services.GetValue<SPWebService>("").WebApplications;
                
                foreach (SPWebApplication webApp in webApps)
                {
                    //pass a parameter to specify if backing up Admin Sites
                    if (webApp.IsAdministrationWebApplication && Settings.Default.backupAdminWebApps == false)
                    {
                        logger.Log(string.Format("Web Application {0} is Administration site and specified to be skiped", webApp.Name));
                        continue;
                    }

                    logger.Log(string.Format("Backing up sites from {0} WebApp", webApp.Name));
                    SPSiteCollection sites = webApp.Sites;
                    foreach (SPSite site in sites)
                    {
                        
                        string filename = GetBackupFileName(rootFolder,webApp,site,DateTime.Now);
                        
                        logger.Log(string.Format("Backing up {0} site collection on {1}", site.Url, filename));
                        
                        try
                        {
                            //Backup Site Collection to file
                            sites.Backup(site.Url, filename, true);
                                                  
                            
                            RemoveOldFiles(rootFolder, webApp, site,logger);
                        }
                        catch(Exception ex)
                        {
                            logger.Log(ex);
                        }

                    }
                }
            }
            catch (Exception ex)
            {
                //Log exception
                logger.Log(string.Format("Error: {0}", ex));
                return false;
            }
            return true;
        }

        
        private static void RemoveOldFiles(string rootFolder, SPWebApplication webApp, SPSite site, Logger logger)
        {
                //remove old files
                int days = Settings.Default.daysToKeepBackups;

                
                DateTime dt = DateTime.Now.AddDays(-days);
                bool FileFound = false;
                do
                {
                    
                    string deleteFile = GetBackupFileName(rootFolder, webApp, site, dt);

                    if (File.Exists(deleteFile))
                    {
                        File.Delete(deleteFile);

                        logger.Log(string.Format("File: {0} expired and was deleted", deleteFile));
                        dt.AddDays(-1);
                        FileFound = true;
                    }
                    else
                        FileFound = false;
                }
                while (FileFound);
        }

        private static string GetBackupFileName(string rootFolder, SPWebApplication webApp, SPSite site, DateTime dt)
        {
            return Path.Combine(rootFolder,string.Format("{0} {1} {2}.bak", webApp.Name, site.ServerRelativeUrl, dt.ToString("yyyy-MM-dd")).Replace('/', '-'));
        }



       

        
        internal static void SendEmail(string subject,Logger loger)
        {
            
            SPAdministrationWebApplication local = SPAdministrationWebApplication.Local;
            SPWeb web = local.Sites[0].RootWeb;
            
            string to = Settings.Default.sendEmailTo;
            string from = local.OutboundMailSenderAddress;

            if (!string.IsNullOrEmpty(to))
            {
                
                    EmailBuilder email = new EmailBuilder(loger);
                    string body = email.Body;

                    File.WriteAllText(Path.Combine(Settings.Default.rootFolder,string.Format("Report {0}.html",DateTime.Now.ToString("yyyy-MM-dd"))), body);

                    System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient();
                    smtp.Host = local.OutboundMailServiceInstance.Server.Address;


                    System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage(from, to);
                    msg.IsBodyHtml = true;
                    msg.Body = body;
                    msg.Subject = subject;

                    smtp.Send(msg);

                    //SharePoint has a 2k Limit for email body so we can't use it.
                    //Microsoft.SharePoint.Utilities.SPUtility.SendEmail(web, true, false, to, subject, body,true);
                    
                    
                    
            
            }
        }

      
    }
}
